package com.manlitech.manlichat.base.netty.util;

import com.alibaba.fastjson.JSON;
import com.manlitech.manlichat.base.exception.MyException;
import com.manlitech.manlichat.base.netty.pool.MyChannelHandlerPool;
import com.manlitech.manlichat.enums.ResultEnums;
import com.manlitech.manlichat.pojo.Result;
import com.manlitech.manlichat.util.ResultUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

/**
 * 消息处理及发送消息
 * @author shensg
 */
@Component
public class MessageSendUtil {

    /**
     * 发送给某个人
     */
    public void sendToSomeone(String fromId,String toId,Result content) {
        ChannelId fromIdChannel = MyChannelHandlerPool.channelIdMap.get(fromId);
        MyChannelHandlerPool.channelGroup.find(fromIdChannel).writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(ResultUtil.success(ResultEnums.SUCCESS_CHAT_TO_ONE_MESSAGE)).toString()));

        ChannelId toIdChannel = MyChannelHandlerPool.channelIdMap.get(toId);
        if(MyChannelHandlerPool.channelGroup.find(toIdChannel) == null){
            throw new MyException(ResultEnums.RECEIVE_IS_OFFLINE);
        }
        MyChannelHandlerPool.channelGroup.find(toIdChannel).writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(content).toString()));
    }

    /**
     * 发送给某些人
     */
    public void sendAllMessage(Result content){
        //收到信息后，群发给所有channel
        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(content).toString()));
    }

    /**
     * channelId和用户绑定
     * @param uid
     * @param channelId
     */
    public void binUidAndChannelId(String uid, ChannelId channelId) {
        MyChannelHandlerPool.channelIdMap.put(uid, channelId);
    }

    /**
     * 服务器响应客户端
     * @param fromId
     * @param content
     */
    public void responseTheRequest(Channel fromId , Result content){
        fromId.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(content).toString()));
    }

    /**
     * 服务器响应客户端 二进制
     * @param fromId
     * @param content
     */
    public void responseTheRequestByBinary(Channel fromId , Result content){
        String msg = JSON.toJSONString(content).toString();
        msg = msg;
        ByteBuf byteBuf = Unpooled.directBuffer(msg.length());
        byteBuf.writeBytes(msg.getBytes());
        fromId.writeAndFlush(new BinaryWebSocketFrame(byteBuf));
    }
}
